/*
 * The WebGrADS Javascript Client Kernel.
 */

function GaWeb() {
    this.session_id = null;
    this.ui = null;
    this.ping_id = null;
}

// Initialize gaweb, which in turn initializes the UI
//
// Params:
//   ui: The GaWebUI instance
GaWeb.prototype.init = function(ui) {
    this.ui = ui;
    var me = this;
    $.getJSON('/ajax', {'task': 'init'}, function(data) {me.handleSuccess(data)});
}

// Ends a session
GaWeb.prototype.endSession = function() {
    $.getJSON('/ajax',
	      {'task': 'end',
	       'session_id': this.session_id},
	      function(data) {});
}

// The centralized success method for AJAX requests performed by this object.
//
// Params:
//   data: the JSON data returned in the AJAX request.
GaWeb.prototype.handleSuccess = function(data) {
    if (data.task == 'init') {
	if (data.error) {
	    if (data.error == 1) {
		alert('You have reached the max sesssion limit. You may not create any new sessions. If you recently closed a session, it will automatically expire shortly.');
	    } else {	   	       
		alert('Service temporarily down.');
	    }
	} else {	    
	    this.session_id = data.session_id;

	    this.ui.init(data['menu']);

	    var me = this;
	    this.ping_id = setInterval(function() {me.ping();},
				       data.ping_interval);
	}
    }
    else if (data.task == 'command') {
       
	if (data.error) {
	    if (data.error === -1) {
		this.ui.term.error('Unknown error.');
	    } else if (data.error === 1) {
		this.ui.term.error('Sorry, it seems your session has expired.');
		this.ui.term.disable();
	    } else if (data.error === 2) {	
		this.ui.term.error('Your session has been terminated (node disconnected). Please refresh the page to start a new session.');
		this.ui.term.disable();
	    } else {
		this.ui.term.error('Unknown error ('+data.error+').');
	    }
	} else {
	    // echo terminal output and resume terminal
	    this.ui.term.echo(data.output);
	    this.ui.term.resume();

	    // If image was sent, display image
	    if (data.image) {
		this.ui.refreshGrADSWindowImage(data.image_data);
	    }

	    this.ui.setLoading(false);

	    // If files were changed, refresh display dialog
	    var me = this;
	    if (data.files_changed) {
		if ($('#display-dialog').length > 0) {
		    $.getJSON('/template',
                              {'template_id': 'display',
			       'session_id': me.session_id},
			      function(data) {
				  me.ui.refreshDisplayDialog(data);
			      });
		}
	    }

	    // If dims were changed, update dims and refresh navigator dialog
	    // and update the sliders
	    if (data.dims_changed) {
		if (('#naviator-dialog').length > 0) {
		    me.ui.refreshNavigatorDialog(data.dims, data.ctlinfo);
		}
		
		me.ui.refreshSliders(data.dims, data.ctlinfo);
	    }

	    // If display expression changed, update the display expression
	    if (data.display_expr_changed) {
		me.ui.last_display_expr = data.display_expr;
		// note: updating title expression here introduces a bug
	    }
	}
    }

    else if (data.task == 'nodestats') {
	this.ui.term.echo(data['text'])
	this.ui.term.resume();
    }

    else if (data.task == 'ping') {
	if (data.error === 1) {
	    clearInterval(this.ping_id);
	    this.ui.term.error('Your session has been terminated.');
	    this.ui.term.disable();
	} else if (data.error === 2) {
	    this.ui.term.error('Your session has been terminated (node disconnected). Please refresh the page to start a new session.');
	}
    }
};

GaWeb.prototype.ping = function() {
    var me = this;
    $.getJSON('/ajax',
	      {'task': 'ping',
	       'session_id': this.session_id,
               'ticks': (new Date()).getTime()},
	      function(data){me.handleSuccess(data)});
}

GaWeb.prototype.handleTerminal = function(command, term) {
    command = $.trim(command);
    if (command.length == 0) {
	return;
    }
    
    this.ui.setLoading(true);


    if (command.split(' ')[0] == '/nodestats') {
	this.ui.term.pause();
	var me = this;
	$.getJSON('/ajax',
		  {'task': 'nodestats',
		   'session_id': this.session_id},
		  function (data) {me.handleSuccess(data)});		  
    } else {
	this.ui.term.pause();
	var me = this;
	$.getJSON('/ajax',
		  {'task': 'command',
		   'session_id': this.session_id,
		   'command': command},
		  function(data) {me.handleSuccess(data);});
    }
}
